package com.xsp.mybatisxmlsqlparser.service;

import cn.hutool.core.io.resource.ResourceUtil;
import com.xsp.mybatisxmlsqlparser.parser.DomParserUtil;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.ExecutorService;

@Service
@Slf4j
public class XMLSQLParser {

    private final ExecutorService taskExecutor;

    private final ReadFilesService readFilesService;

    public XMLSQLParser(ReadFilesService readFilesService, ExecutorService taskExecutor) {
        this.readFilesService = readFilesService;
        this.taskExecutor = taskExecutor;
    }

    public void convertAndParseXML(String absolutePath, String outputPath) {
        List<File> files = readFilesService.readFiles(absolutePath, ".xml");
        log.info("一共读取到 ${files.size} 个文件");
        for (File file : files) {
            taskExecutor.submit(() -> {
                log.info("开始转换文件");
                try {
                    SAXReader reader = new SAXReader();
                    String xmlString = ResourceUtil.readStr("conversion/TestMain.xml", StandardCharsets.UTF_8);
                    Document document = reader.read(new ByteArrayInputStream(xmlString.getBytes(StandardCharsets.UTF_8)));
                    Element root = document.getRootElement();
                    // 获取根元素的所有子元素
                    List<Element> childElements = root.elements();
                    //检查内容
                    DomParserUtil.checkElementLabels(childElements);
                    List<Element> selectElements = root.elements("select");
                } catch (Exception e) {
                    log.error("解析文件失败: ${file.getName()}");
                    log.error(e.getMessage());
                }
                log.info("文件转换完成: ${file.getName()}");
            });
        }
        taskExecutor.shutdown();

    }
}
